package com.example.fangyimanagement;

import com.example.fangyimanagement.core.BizException;
import com.example.fangyimanagement.core.LoginUser;
import com.example.fangyimanagement.core.MyJson;
import com.example.fangyimanagement.core.Result;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RestController
@RequestMapping("/menuManage")
public class MenuManageController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    /**
     * 添加菜单
     * @param param
     * @return
     */
    @RequestMapping("/addMenu")
    public Result<Void> addMenu(@RequestBody Map<String, String> param) {
        String pid = param.get("pid");
        String code = param.get("code");
        String title = param.get("title");
        String menuType = param.get("menuType");
        String path = param.get("path");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "insert into glpt_menu (pid, code, title, type, path, create_time, remark) " +
                "values (?, ?, ?, ?, ?, CURRENT_TIME, ?)";
        int rows = this.jdbcTemplate.update(sql, pid, code, title, menuType, path, remark);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("添加失败");
        }
    }

    /**
     * 删除菜单
     * @param param
     * @return
     */
    @RequestMapping("/deleteMenu")
    public Result<Void> deleteMenu(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        //        操作数据库
        int rows = this.jdbcTemplate.update("delete from glpt_menu where id =?", id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("没找到这个菜单");
        }
    }

    /**
     * 编辑菜单
     * @param param
     * @return
     */
    @RequestMapping("/updateMenu")
    public Result<Void> updateMenu(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String pid = param.get("pid");
        String code = param.get("code");
        String title = param.get("title");
        String menuType = param.get("menuType");
        String path = param.get("path");
        String remark = param.get("remark");
        //        操作数据库
        String sql = "update glpt_menu set pid=?, code=?, title=?, type=?, path=?, remark=? where id =?";
        int rows = this.jdbcTemplate.update(sql, pid, code, title, menuType, path, remark, id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("编辑失败");
        }
    }

    /**
     * 查询菜单列表
     * @param param
     * @return
     */
    @RequestMapping("/menuList")
    public Result<List<Map<String, Object>>> menuList(@RequestBody Map<String, String> param) {
        String account = param.get("account");
        String sql = "SELECT CAST(glpt_menu.id AS CHAR) AS id, CAST(pid AS CHAR ) AS pid, code, title, type, path, glpt_menu.create_time AS createTime, glpt_menu.remark, menu_role.role_code, glpt_user.account FROM glpt_menu " +
                "JOIN menu_role ON glpt_menu.code = menu_role.menu_code " +
                "JOIN glpt_user ON glpt_user.role_code = menu_role.role_code " +
                "WHERE account = ?";
        List<Map<String, Object>> authorizedMenus = this.jdbcTemplate.queryForList(sql, account);
        return Result.success(authorizedMenus);
    }

    /**
     * 根据父级菜单id查询子菜单列表
     * @param param
     * @return
     */
    @RequestMapping("/menuTreeList")
    public Result<List<Map<String, Object>>> menuTreeList(@RequestBody Map<String, String> param) {
        String sql = "SELECT CAST(id AS CHAR) AS id, CAST(pid AS CHAR ) AS pid, code, title, type, path, create_time, remark FROM glpt_menu";
        String pid = param.get("pid");
        if (pid != null && !pid.isEmpty()) {
            sql = sql + " WHERE pid = '" + pid + "'";
        }
        List<Map<String, Object>> orgList = this.jdbcTemplate.queryForList(sql);
        return Result.success(orgList);
    }

    /**
     * 查询菜单授权的菜单角色关系表
     * @param param
     * @return
     */
    @RequestMapping("/menuRoleList")
    public Result<List<Map<String, Object>>> menuRoleList(@RequestBody Map<String, String> param) {
        String sql = "SELECT glpt_role.role_code AS roleCode, glpt_role.role_name AS roleName FROM menu_role" +
                " JOIN glpt_role ON menu_role.role_code = glpt_role.role_code";
        String menuCode = param.get("menuCode");
        if (menuCode != null && !menuCode.isEmpty()) {
            sql = sql + " WHERE menu_code = '" + menuCode + "'";
        }
        List<Map<String, Object>> orgList = this.jdbcTemplate.queryForList(sql);
        return Result.success(orgList);
    }

    /**
     * 授权
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/setMenuRole")
    public Result<Void> setMenuRole(@RequestBody Map<String, Object> param, LoginUser loginUser) {
        @SuppressWarnings("unchecked")
        List<String> menuCodes = (List<String>) param.get("menuCodes");
        @SuppressWarnings("unchecked")
        List<String> roleCodes = (List<String>) param.get("roleCodes");

        if (CollectionUtils.isEmpty(menuCodes) || roleCodes == null) {
            throw new BizException("请求参数错误");
        }

        // 先把历史数据（该菜单之前授权的所有角色）都删掉
        this.namedParameterJdbcTemplate.update("DELETE FROM menu_role WHERE menu_code IN (:menuCodes) AND role_code IN (:roleCodes)", MyJson.of(
                "menuCodes", menuCodes,
                "roleCodes", roleCodes
        ));

        if (!menuCodes.isEmpty() && !roleCodes.isEmpty()) {
            List<Object[]> paramList = new ArrayList<>();
            for (String roleCode : roleCodes) {
                for (String menuCode : menuCodes) {
                    paramList.add(new Object[] {menuCode, roleCode});
                }
            }

            this.jdbcTemplate.batchUpdate("INSERT INTO menu_role (menu_code, role_code) VALUES (?, ?)", paramList);
        }
        return Result.success();
    }

    /**
     * 移除权限
     * @param param
     * @param loginUser
     * @return
     */
    @RequestMapping("/removeMenuRole")
    public Result<Void> removeMenuRole(@RequestBody Map<String, Object> param, LoginUser loginUser) {
        String menuCode = Objects.toString(param.get("menuCode"), null);
        List<String> removeRoleList = (List<String>) param.get("removeRoleList");
        //        操作数据库
        int rows = this.namedParameterJdbcTemplate.update(
                "DELETE FROM menu_role WHERE menu_code = :menuCode and role_code IN (:removeRoleList)",
                MyJson.of(
                        "removeRoleList", removeRoleList,
                        "menuCode", menuCode
                )
        );
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.failed("操作失败");
        }
    }
}
